package com.educate.book.rpc.provide.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.educate.common.utils.converter.ListUtils;
import com.educate.common.utils.exception.AppException;
import com.educate.common.web.BeanUtils;
import com.educate.book.dao.BookPageDao;
import com.educate.book.model.bo.BookPageBO;
import com.educate.book.model.po.BookPage;
import com.educate.book.rpc.api.BookPageService;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;

@Log4j2
@Service(
        version = "${api.service.version}",
        application = "${dubbo.application.id}",
        protocol = "${dubbo.protocol.id}",
        registry = "${dubbo.registry.id}"
)
public class BookPageServiceImpl implements BookPageService {

    @Resource BookPageDao bookPageDao;

    @Override
    public void create(BookPageBO bo) {
        bookPageDao.insert(bo);
    }

    @Override
    public void delete(BookPageBO bo) {
        bookPageDao.delete(bo);
    }

    @Override
    public void delete(String bookPageId) {
        bookPageDao.deleteById(bookPageId);
    }

    @Override
    public BookPageBO detail(String bookPageId) {
        Optional<BookPage> optional = bookPageDao.findById(bookPageId);
        if (!optional.isPresent()) {
            throw new AppException("不存在的实例");
        }
        return new BookPageBO(optional.get());
    }

    @Override
    public BookPageBO detail(BookPageBO bo) {
//        return detail(bo.getOrganizationId());
        return null;
    }

    @Override
    public void update(BookPageBO bo) {
        Optional<BookPage> optional = bookPageDao.findById(bo.getBookPageId());
        if (!optional.isPresent()) {
            throw new AppException("不存在的实例");
        }
        BeanUtils.copyPropertiesNonEmpty(bo, optional.get());
        bookPageDao.save(optional.get());
    }

    @Override
    public Page<BookPageBO> query(BookPageBO bo, PageRequest pageRequest) {
        return bookPageDao.query(bo, pageRequest).map(BookPageBO::new);
    }

    @Override
    public List<BookPageBO> list(BookPageBO bo) {
        List<BookPage> result = bookPageDao.findAll();
        return ListUtils.map(result, BookPageBO::new);
    }
}
